package com.zhiyou.homework.service.impl;

import com.zhiyou.common.pojo.Result;
import com.zhiyou.common.pojo.StateCode;
import com.zhiyou.homework.compare.CourseCompare;
import com.zhiyou.homework.compare.GradeCompare;
import com.zhiyou.homework.dao.*;
import com.zhiyou.homework.pojo.*;
import com.zhiyou.homework.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.util.stream.Collectors.toList;

@Service
public class TeacherServiceImpl implements TeacherService {


    @Autowired
    private GradeDao gradeDao; // 班级
    @Autowired
    private CourseDao courseDao; // 科目

    @Autowired
    private GradeCourseDao gradeCourseDao;// 班级科目关联

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private StudentHomeworkDao stuHwDao;

    /**
     * 根据教师id查询科目和班级
     * @param tid
     * @return
     */
    @Override
    public Map<String, TreeSet> findGradeAndCourseByTeacherId(Integer tid) {
        // 存放查出的班级信息
        TreeSet<Grade> gradeSet = new TreeSet<>(new GradeCompare());
        // 存放查出的科目信息
        TreeSet<Course> courseSet = new TreeSet<>(new CourseCompare());
       // 根据tid查询班级科目表
        GradeCourse gradeCourseObj = new GradeCourse();
        gradeCourseObj.setTid(tid);
        List<GradeCourse> gradeCourseList = gradeCourseDao.select(gradeCourseObj);
        for (GradeCourse gradeCourse : gradeCourseList) {
            // 得到每个班级编号,再查班级信息
            Grade grade = gradeDao.selectByPrimaryKey(gradeCourse.getGid());
            gradeSet.add(grade);
            // 得到科目编号,再查科目信息
            Course course = courseDao.selectByPrimaryKey(gradeCourse.getCid());
            courseSet.add(course);
        }
        Map<String,TreeSet> gradeCourseMap = new HashMap<>();
        gradeCourseMap.put("grade",gradeSet);
        gradeCourseMap.put("course",courseSet);
        return gradeCourseMap;
    }

    /**
     *根据班级id查询学生信息 及 作业完成状态
     * @param paramMap 参数数组,内含 教师id 班级id 作业状态 作业发布时间
     * @return
     */
    @Override
    public List<StudentExt> findStuNameAndStatusByGid(Map<String,Object> paramMap) {

        List<StudentExt> studentExtList = new ArrayList<>();
        Integer tid = (Integer) paramMap.get("tid");
        Integer gradeId = (Integer) paramMap.get("gradeId");
        Integer statusCode = (Integer) paramMap.get("statusCode");
        Student stu = new Student();
        stu.setSgid(gradeId);
        // 根据班级id返回所有学生信息
        List<Student> studentList = studentDao.select(stu);
        for (Student student : studentList) {
            // 根据学生id及教师id及作业发布时间 (当前时间)查询作业信息
            Example example = new Example(StudentHomework.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("shsid",student.getSid());
            criteria.andEqualTo("shtid",tid);
            if (statusCode == null && paramMap.get("releaseTime") == null) {
                criteria.andLike("shreleasetime","%"+new SimpleDateFormat("yyyy-MM-dd").format(new Date(120,7,6))+"%");
            } else if (statusCode != 4){
                criteria.andEqualTo("shstatus",paramMap.get("statusCode").toString());
                criteria.andLike("shreleasetime","%"+paramMap.get("releaseTime").toString()+"%");
            } else if(statusCode == 4) {
                criteria.andLike("shreleasetime","%"+paramMap.get("releaseTime").toString()+"%");
            }
            StudentHomework studentHomework = stuHwDao.selectOneByExample(example);
            if (studentHomework != null) {
                StudentExt studentExt = new StudentExt(student);
                studentExt.setShstatus(studentHomework.getShstatus());
                studentExt.setShsubtime(studentHomework.getShsubtime());
                studentExt.setShreleasetime(studentHomework.getShreleasetime());
                studentExtList.add(studentExt);
            }
        }
        if (statusCode == 4) {
            List<Integer> allSid = new ArrayList<>();
            for (Student student : studentList) {
                allSid.add(student.getSid());
            }
            List<Integer> subSid = new ArrayList<>();
            for (StudentExt studentExt : studentExtList) {
                subSid.add(studentExt.getSid());
            }

            List<Integer> reduce = allSid.stream().filter(item -> !subSid.contains(item)).collect(toList());
            Example example = new Example(Student.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("sid",reduce);
            List<Student> students = studentDao.selectByExample(example);
            studentExtList = new ArrayList<>();
            for (Student student : students) {
                studentExtList.add(new StudentExt(student));
            }
        }

        return studentExtList;
    }


    /**
     * 查询单个学生作业详情
     * @param sid 学生id
     * @param tid 教师id
     */
    @Override
    public StudentHomeworkExt findOneHwInfoBySid(Integer sid, Integer tid) {
        // 返回学生名
        Student student = studentDao.selectByPrimaryKey(sid);
        // 返回班级名
        Grade grade = gradeDao.selectByPrimaryKey(student.getSgid());
        // 返回科目名
        GradeCourse gradeCourseParam = new GradeCourse();
        gradeCourseParam.setTid(tid);
        gradeCourseParam.setGid(grade.getGid());
        GradeCourse gradeCourse = gradeCourseDao.selectOne(gradeCourseParam);
        Course course = courseDao.selectByPrimaryKey(gradeCourse.getCid());
        // 返回该学生作业信息
        StudentHomework stuHwParam = new StudentHomework();
        stuHwParam.setShtid(tid);
        stuHwParam.setShsid(sid);
        StudentHomework studentHomework = stuHwDao.selectOne(stuHwParam);
        StudentHomeworkExt studentHomeworkExt = new StudentHomeworkExt(studentHomework);
        studentHomeworkExt.setStuname(student.getSname());
        studentHomeworkExt.setCoursename(course.getCname());
        studentHomeworkExt.setClassname(grade.getGname());
        return studentHomeworkExt;
    }

    @Override
    public boolean checkHomework(Integer sid, Integer tid, Integer statusCode,String subTime) {
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("sid",sid.toString());
        paramMap.put("tid",tid.toString());
        paramMap.put("statusCode",statusCode.toString());
        paramMap.put("subTime",subTime);
        int rowNum = stuHwDao.updateHomeworkstatus(paramMap);
        if (rowNum > 0 ){
            return true;
        }
        return false;
    }

    @Override
    public Result releaseHomeworkImgOrVideo(MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(false, StateCode.ERROR,"作业发布图片或视频失败");
        }

        String fileName = file.getOriginalFilename();
        String filePath = "E:\\IDEA-WorkSpace\\fly_elephant\\fly_homework\\upload\\";
        String[] split = fileName.split("\\.");
        String suffix = split[1];
        // 以当前毫秒值为文件名
        long prefix = new Date().getTime();
        // 组装文件名
        String newFileName = prefix+"."+suffix;
        File dest = new File(filePath + newFileName);
        try {
            file.transferTo(dest);
            return new Result(true, StateCode.OK,"作业发布图片或视频成功",dest.getAbsolutePath());
        } catch (IOException e) {
            System.out.println("上传文件异常!");
            return new Result(false, StateCode.ERROR,"作业发布图片或视频失败");
        }
    }


}
